package com.xindaoapp.happypet.ui;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.MyClubActivity;
import com.xindaoapp.happypet.bean.Groups;
import com.xindaoapp.happypet.bean.Groups.Group;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.ProgressHUD;
import com.xindaoapp.happypet.view.CircleImageView;

/**
 * 添加圈子
 * 
 * @author
 * 
 */
public class AddGroupActivity extends BaseActivity {
    private ListView vOneList;
    private PullToRefreshListView vTwoList;
    private RelativeLayout vNoresult;

    private List<Group> mOneGroups;

    private GroupOneAdapter mOneAdapter;

    private List<Group> mTwoGroups;

    private GroupTwoAdapter mTwoAdapter;
    private String fid = "";

    private LoginSuccessReceiver loginSuccessReceiver;
    private JoinOutReciver joinOutReciver;


    @Override
    protected int getContentViewResId() {
        return R.layout.activity_addgroup;
    }

    @Override
    protected void initViews() {
        setTopBarTitle("加入圈子");
        vOneList = (ListView) findViewById(R.id.group_one);
        vTwoList = (PullToRefreshListView) findViewById(R.id.group_two);
        vNoresult = (RelativeLayout) findViewById(R.id.noresult);
        super.initViews();
    }

    @Override
    protected void initEvents() {
        vTwoList.setMode(PullToRefreshBase.Mode.DISABLED);
        vOneList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (vNoresult.getVisibility() == View.VISIBLE) {
                    vNoresult.setVisibility(View.GONE);
                }
                if (vTwoList.getVisibility() == View.GONE) {
                    vTwoList.setVisibility(View.VISIBLE);
                }
                if (null != mOneGroups && mOneGroups.size() > 0) {
                    loadTwoList(mOneGroups.get(position).fid);
                    fid = mOneGroups.get(position).fid;
                    mOneAdapter.setSelectedPosition(position);
                    mOneAdapter.notifyDataSetChanged();
                }
            }
        });
        vTwoList.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (null != mTwoGroups && mTwoGroups.size() > 0) {
                    // Intent intent = new Intent(AddGroupActivity.this, ClubDetailActivity.class);
                    Intent intent = new Intent(AddGroupActivity.this, MyClubActivity.class);
                    if ("1".equals(mTwoGroups.get(position - 1).isjoin)) {
                        Constants.ISMYGROUP = true;
                    } else {
                        Constants.ISMYGROUP = false;
                    }
                    intent.putExtra("name", mTwoGroups.get(position - 1).name);
                    intent.putExtra("fId", mTwoGroups.get(position - 1).fid);
                    startActivity(intent);
                }

            }
        });
        loginSuccessReceiver = new LoginSuccessReceiver();
        registerReceiver(loginSuccessReceiver, new IntentFilter(
                Constants.ACTION_LOGIN_STATE_CHANGED));
        joinOutReciver = new JoinOutReciver();
        registerReceiver(joinOutReciver, new IntentFilter(Constants.JOIN_OUT_GROUP));
        super.initEvents();
    }

    // @Override
    // protected void loadDatas() {
    // // loading.setVisibility(View.GONE);
    // super.loadDatas();
    // }
    @Override
    protected void onLoadDatas() {
        loadOneList();
        super.onLoadDatas();
    }

    private boolean isFirst = true;

    private void loadOneList() {
        if (CommonUtil.checkNetState(AddGroupActivity.this)) {
            getMoccaApi().getOneGroups(new IRequest<Groups>() {
                @Override
                public void request(Groups t) {
                    if (null == t) {
                        if (isFirst) {
                            onDataArrived(false);
                        }
                    } else {
                        isFirst = false;
                        if (t.getResult().equals("0")) {
                            onDataArrived(true);
                            if (t.array != null && t.array.size() > 0) {
                                mOneGroups = t.array;
                                mOneAdapter = new GroupOneAdapter(mOneGroups);
                                vOneList.setAdapter(mOneAdapter);
                                loadTwoList(mOneGroups.get(0).fid);
                                fid = mOneGroups.get(0).fid;
                            }
                        } else {
                            if (!TextUtils.isEmpty(t.getMsg())) {
                                onDataArrived(false);
                            }
                        }
                    }
                }
            });
        } else {
            if (isFirst) {
                onDataArrived(false);
            }
        }
    }

    private void loadTwoList(String fid) {
        getMoccaApi().getTwoGroups(fid, new IRequest<Groups>() {
            @Override
            public void request(Groups t) {
                if (null == t) {
                    vNoresult.setVisibility(View.VISIBLE);
                    vTwoList.setVisibility(View.GONE);
                } else {
                    if (t.getResult().equals("0")) {
                        if (t.array != null && t.array.size() > 0) {
                            mTwoGroups = t.array;
                            mTwoAdapter = new GroupTwoAdapter(mTwoGroups);
                            vTwoList.setAdapter(mTwoAdapter);
                            mTwoAdapter.notifyDataSetChanged();
                        }
                    } else {
                        if (!TextUtils.isEmpty(t.getMsg())) {
                            Toast.makeText(AddGroupActivity.this, t.getMsg(), Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
                }
            }
        });
    }

    private class GroupOneAdapter extends BaseAdapter {
        int selectedPosition = 0;
        private final List<Group> groups;

        public GroupOneAdapter(List<Group> groups) {
            super();
            this.groups = groups;
        }

        @Override
        public int getCount() {
            return groups.size();
        }

        @Override
        public Object getItem(int position) {
            return groups.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        @SuppressWarnings("static-access")
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolderGood holder;
            if (convertView == null) {
                convertView = View.inflate(AddGroupActivity.this, R.layout.goods_one_item, null);
                holder = new ViewHolderGood();
                holder.imageView1 = (ImageView) convertView.findViewById(R.id.imageView1);
                holder.check = (CheckedTextView) convertView.findViewById(R.id.goods_one_check);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolderGood) convertView.getTag();
            }
            if (selectedPosition == position) {
                holder.check.setTextColor(Color.parseColor("#f46e58"));
                holder.check.setTextSize(18);
                holder.imageView1.setVisibility(View.VISIBLE);
                // convertView.setBackgroundResource(R.drawable.addgroup_bg_selected);
            } else {
                holder.check.setTextColor(Color.parseColor("#ff71624f"));
                holder.check.setTextSize(16);
                holder.imageView1.setVisibility(View.GONE);
                // convertView.setBackgroundResource(R.drawable.addgroup_bg_default);
            }
            holder.check.setText(groups.get(position).name);
            return convertView;
        }
    }

    class ViewHolderGood {
        CheckedTextView check;
        ImageView imageView1;
    }
    private class GroupTwoAdapter extends BaseAdapter {
        private final List<Group> groups;

        public GroupTwoAdapter(List<Group> groups) {
            super();
            this.groups = groups;
        }

        @Override
        public int getCount() {
            return groups.size();
        }

        @Override
        public Object getItem(int position) {
            return groups.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public List<Group> getItems() {
            if (null != groups) {
                return groups;
            }
            return null;
        }

        public void ClearItems() {
            groups.clear();
        }

        public void addItems(List<Group> gs) {
            if (null != groups) {
                groups.addAll(gs);
                getCount();
                notifyDataSetChanged();
            }
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewTwoHolder holder;
            if (convertView == null) {
                holder = new ViewTwoHolder();
                convertView = View.inflate(AddGroupActivity.this, R.layout.group_two_items, null);
                holder.add_delete = (ImageView) convertView.findViewById(R.id.add_delete);
                holder.iv_item_list = (CircleImageView) convertView.findViewById(R.id.iv_item_list);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                holder.tv_num = (TextView) convertView.findViewById(R.id.tv_num);
                convertView.setTag(holder);
            } else {
                holder = (ViewTwoHolder) convertView.getTag();
            }
            /** 1为加入过了 0为未加入 */
            if (!TextUtils.isEmpty(groups.get(position).isjoin)) {
                if (groups.get(position).isjoin.equals("1")) {
                    holder.add_delete.setBackgroundResource(R.drawable.add_to_group_false);
                } else if (groups.get(position).isjoin.equals("0")) {
                    holder.add_delete.setBackgroundResource(R.drawable.add_to_group);
                }
            } else {
                holder.add_delete.setBackgroundResource(R.drawable.add_to_group);
            }
            ImageLoader.getInstance().displayImage(groups.get(position).ico, holder.iv_item_list);
            if (!TextUtils.isEmpty(groups.get(position).name)) {
                holder.name.setText(groups.get(position).name);
            }

            holder.tv_num.setText(groups.get(position).membernum);

            holder.add_delete.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (TextUtils.isEmpty(groups.get(position).isjoin)
                            || groups.get(position).isjoin.equals("0")) {
                        if (UserState.isLogged(AddGroupActivity.this)) {
                            if (CommonUtil.checkNetState(AddGroupActivity.this)) {
                                final ProgressHUD ProgressDialog =
                                        ProgressHUD.show(AddGroupActivity.this, "正在加载...", true,
                                                true, null);
                                getMoccaApi().joinGroup(groups.get(position).fid,
                                        AddGroupActivity.this, new IRequest<Boolean>() {
                                            @Override
                                            public void request(Boolean t) {
                                                if (null != ProgressDialog
                                                        && ProgressDialog.isShowing()) {
                                                    ProgressDialog.dismiss();
                                                }
                                                if (t) {
                                                    holder.add_delete
                                                            .setBackgroundResource(R.drawable.add_to_group_false);
                                                    groups.get(position).isjoin = "1";
                                                    notifyDataSetChanged();
                                                } else {
                                                    holder.add_delete
                                                            .setBackgroundResource(R.drawable.add_to_group);
                                                }
                                                sendBroadcast(new Intent(Constants.JOIN_OUT_GROUP));
                                            }
                                        });
                            } else {
                                Toast.makeText(getApplicationContext(),
                                        R.string.pLease_check_network, Toast.LENGTH_SHORT).show();
                            }
                        }
                    } else if (groups.get(position).isjoin.equals("1")) {
                        if (UserState.isLogged(AddGroupActivity.this)) {
                            if (UserState.isLogged(AddGroupActivity.this)) {
                                final ProgressHUD ProgressDialog =
                                        ProgressHUD.show(AddGroupActivity.this, "正在加载...", true,
                                                true, null);
                                getMoccaApi().outGroup(groups.get(position).fid,
                                        AddGroupActivity.this, new IRequest<Boolean>() {
                                            @Override
                                            public void request(Boolean t) {
                                                if (null != ProgressDialog
                                                        && ProgressDialog.isShowing()) {
                                                    ProgressDialog.dismiss();
                                                }
                                                if (t) {
                                                    holder.add_delete
                                                            .setBackgroundResource(R.drawable.add_to_group);
                                                    groups.get(position).isjoin = "0";
                                                    notifyDataSetChanged();
                                                } else {
                                                    holder.add_delete
                                                            .setBackgroundResource(R.drawable.add_to_group_false);
                                                }
                                                sendBroadcast(new Intent(Constants.JOIN_OUT_GROUP));
                                            }
                                        });
                            } else {
                                Toast.makeText(getApplicationContext(),
                                        R.string.pLease_check_network, Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }
            });
            return convertView;
        }
    }
    private class ViewTwoHolder {
        ImageView add_delete;
        CircleImageView iv_item_list;
        TextView name, tv_num;
    }

    @Override
    protected OnClickListener getLeftViewClickListener() {
        return new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        };
    }

    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
    }


    private class JoinOutReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            loadTwoList(fid);
        }
    }

    private class LoginSuccessReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            loadTwoList(fid);
        }
    }

    @Override
    protected void onDestroy() {
        if (null != loginSuccessReceiver) {
            unregisterReceiver(loginSuccessReceiver);
        }
        if (joinOutReciver != null) {
            unregisterReceiver(joinOutReciver);
        }
        super.onDestroy();
    }
}
